"""
Interface to repository back end systems.
"""


# ================================
# = Dynamic Backends for Modules =
# ================================

def load_backend(setting_name, default_name=None):
    """
    Dynamically loads a backend module from the specified django settings
    name, or falling back to the default value if the settings is empty
    or unspecified in the settings.
    """
    backend_name = None
    from django.conf import settings as django_settings
    if hasattr(django_settings, setting_name):
        backend_name = getattr(django_settings, setting_name) or default_name
    else:
        backend_name = default_name
    
    if backend_name:
        return __import__(backend_name, '', '', [''])
    else:
        raise ImportError, 'No backend module specified for %s in Django settings, and no default available.' % setting_name


backend_map = {
    'svn': {
        'name': 'Subversion',
        'module': load_backend('vcs.backends.svn', 'vcs.backends.svn')
    },
    #'hg': {
    #    'name': 'Mercurial',
    #    'module': load_backend('vcs.backends.hg', 'vcs.backends.hg')
    #},
    #'git': {
    #    'name': 'Git',
    #    'module': load_backend('vcs.backends.git', 'vcs.backends.gh')
    #}
}

def get_backend(name):
    """
    Gets the specified repository backend module.
    """
    if name not in backend_map:
        backend_map[name] = {
            'name': name.title(),
            'module': load_backend('vcs.backends.%s' % name)
        }
    return backend_map[name]['module']
